<template>
  <div class="scene_box">
    <p>UV动画</p>
    <div class="canvas"></div>
  </div>
</template>
      
 <script setup>
import { nextTick } from "vue";
import img from "../../js/chapter5/jindu.png";
import * as THREE from "three";
// 引入threejs 的扩展库  相机轨道控件
import { OrbitControls } from "three/addons/controls/OrbitControls.js";

nextTick(() => {
  // ******************创建一个场景*************
  // 一个矩形平面几何体用来表示传送带
  const geometry = new THREE.PlaneGeometry(200, 20);
  //纹理贴图加载器TextureLoader
  const texLoader = new THREE.TextureLoader();
  // .load()方法加载图像，返回一个纹理对象Texture
  const texture = texLoader.load(img);
 
  const material = new THREE.MeshLambertMaterial({
    map: texture, //map表示材质的颜色贴图属性
  });
  const mesh = new THREE.Mesh(geometry, material);
  mesh.rotateX(-Math.PI / 2);
  // 设置.wrapS也就是U方向，纹理映射模式(包裹模式)
  texture.wrapS = THREE.RepeatWrapping; //对应offste.x偏移
  // --------------------------------------------------------
  //场景
  const scene = new THREE.Scene();
  scene.add(mesh); //模型对象添加到场景中

  //辅助观察的坐标系
  const axesHelper = new THREE.AxesHelper(100);
  scene.add(axesHelper);

  //光源设置
  const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
  directionalLight.position.set(100, 60, 50);
  scene.add(directionalLight);
  const ambient = new THREE.AmbientLight(0xffffff, 0.4);
  scene.add(ambient);

  //渲染器和相机
  let dom = document.querySelector(".canvas");
  const width = dom.offsetWidth;
  const height = dom.offsetHeight;
  const camera = new THREE.PerspectiveCamera(30, width / height, 1, 3000);
  camera.position.set(292, 223, 185);
  camera.lookAt(0, 0, 0);

  const renderer = new THREE.WebGLRenderer({
    antialias: true, //去除锯齿
  });
  renderer.setSize(width, height);
  dom.appendChild(renderer.domElement);
// ---------------------------------------------------
  // 渲染循环
  function render() {
    texture.offset.x -= 0.002; //设置纹理动画
    renderer.render(scene, camera);
    requestAnimationFrame(render);
  }
  render();

  const controls = new OrbitControls(camera, renderer.domElement);

  // 画布跟随窗口变化
  window.onresize = function () {
    renderer.setSize(window.innerWidth, window.innerHeight);
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
  };
  renderer.setPixelRatio(window.devicePixelRatio);
});
</script>
      
      
<style  scoped>
.canvas {
  width: 80vw;
  height: 60vh;
}
</style>